package com.citycloud.ccuap.tc.admin.projectrole;

import com.citycloud.ccuap.commons.json.CheckedTreeNode;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.model.ISysUser;
import com.citycloud.ccuap.commons.openapi.controller.base.BaseController;
import com.citycloud.ccuap.commons.web.util.ResolveRequest;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.framework.util.StringUtil;
import com.citycloud.ccuap.tc.admin.datagroup.IDatagroupService;
import com.citycloud.ccuap.tc.admin.entity.SysDatagroup;
import com.citycloud.ccuap.tc.admin.entity.SysProjectDgRoleRel;
import com.citycloud.ccuap.tc.admin.projectdgrolerel.IProjectDgRoleRelService;
import com.citycloud.ccuap.tc.admin.sec.secuser.ISecUserCacheService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@Api("项目（站点）角色")
@RestController
@RequestMapping("/v1/sys/role")
public class ProjectRoleController  extends BaseController {


	@Autowired
	private ISecUserCacheService secUserCacheService;
	@Autowired
	private IProjectRoleService projectRoleService;
	@Autowired
	private IProjectDgRoleRelService projectDgRoleRelService;
	@Autowired
	private IDatagroupService datagroupService;
//	@Autowired
//	private YqService yqService;


	/**
	 * 默认构造函数
	 */
	public ProjectRoleController() {
	}
	@ApiOperation("菜单角色")
	@RequestMapping({"/importRole"})
	public JSONData importProjectFunction(){
		MultipartFile file = this.getFileParameter("file");
		Long projectId = getProjectId();
		ISysUser user = getCurrentUser().getUser();
		if(projectId==null){
			return new JSONData(false,"用户信息已过期");
		}
		try {
			InputStream is = file.getInputStream();
			projectRoleService.importRole(is,projectId,user.getUserNo());
		}catch(Exception e){
			return new JSONData(false,e.getMessage());
		}
		return new JSONData("导入成功！");
	}

	/**
	 * 查询当前站点下所有数据组
	 * @return
	 * @throws Exception
	 */
	@ApiOperation("查询当前站点下所有数据组")
	@RequestMapping(value = "/queryDatagroup", method = RequestMethod.POST)
	public JSONData queryDatagroup() throws Exception {
		PageQuery<Map<String,Object>> pageQuery = ResolveRequest.getPageForParams(request);
		Long projectId=getProjectId();
		String name = getStringParameter("q_name");
        String sql="select sd.* from sys_datagroup sd,sys_project_dg_rel spd where sd.datagroup_id=spd.datagroup_id and spd.project_id= "+projectId;
		if(StringUtils.isNoneBlank(name)) {
			sql+=" and (sd.datagroup_code like '%"+name+"%' or sd.datagroup_name like '%"+name+"%')";
		}
        PageQuery<Map<String, Object>> pageData = projectRoleService.selectPage(pageQuery, sql, true);
		JSONData jsonData = new JSONData(pageData);
		return jsonData;
	}
	
	@ApiOperation("更新数据组权限")
	@RequestMapping(value = "/updateActData", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData updateActData(){
		Long roleId = getLongParameter("roleId");
		String[] actDataids = getStringParameter("actDataids").split("#");
		projectDgRoleRelService.deleteByRoleId(roleId);
		for(String id : actDataids) {
			if(StringUtils.isNotBlank(id)) {
				SysProjectDgRoleRel actData = new SysProjectDgRoleRel();
				actData.setRoleId(roleId);
				actData.setDatagroupId(id);
				projectDgRoleRelService.save(actData);
			}
		}
		secUserCacheService.buildRoleDataGroupCache(roleId);
		JSONData jsonData = new JSONData("成功");
		return jsonData;
	}

	/**
	 * 查询当前站点，当前角色下已有数据组
	 * @return
	 */
	@ApiOperation("获取数据组权限")
	@RequestMapping(value = "/getDataGroup", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData getDataGroup(){
		List<SysDatagroup> result = datagroupService.findDataGroupByRoleId(getLongParameter("roleId"),getProjectId());
		JSONData jsonData = new JSONData(result);
		return jsonData;
	}

	@ApiOperation("admin查找全部功能树节点")
	@RequestMapping(value = "/findAdminAllProjectFunNodeTree", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findAdminAllProjectFunNodeTree() throws Exception {
		Long roleId = getLongParameter("roleId");
		Long projectId = getLongParameter("projectId");
		List<CheckedTreeNode> treeNodeList = projectRoleService.findAllProjectFunNodeTree(roleId,projectId);

		JSONData jsonData = new JSONData(treeNodeList);
		return jsonData;
	}

	@ApiOperation("查找全部功能树节点")
	@RequestMapping(value = "/findAllProjectFunNodeTree", method = { RequestMethod.GET, RequestMethod.POST })
	public JSONData findAllProjectFunNodeTree() throws Exception {
		Long roleId = getLongParameter("roleId");
		List<CheckedTreeNode> treeNodeList = projectRoleService.findAllProjectFunNodeTree(roleId, getProjectId());

		JSONData jsonData = new JSONData(treeNodeList);
		return jsonData;
	}
	
	@ApiOperation("角色授权")
	@RequestMapping(value = "/grantProjectFunction", method = RequestMethod.POST)
	public JSONData grantProjectFunction() throws Exception {
		String funIds = getStringParameter("funIds");
		Long roleId = getLongParameter("roleId");
		List<String> funIdList = StringUtil.strToStringList(funIds);
		projectRoleService.grantFunction(roleId, funIdList);

		JSONData jsonData = new JSONData("角色授权成功！");
		return jsonData;
	}
	
	@ApiOperation("人员分配")
	@RequestMapping(value = "/grantRoleToUsersV2", method = RequestMethod.POST)
	public JSONData grantRoleToUsersV2(HttpServletRequest request) throws Exception {
		String userIds = getStringParameter("userIds");
		String deptIds = getStringParameter("deptIds");
		Long roleId = getLongParameter("roleId");
		String addUserIds = getStringParameter("addUserIds");
		String delUserIds = getStringParameter("delUserIds");
		List<Long> userIdList = StringUtil.strToLongList(userIds);
		List<Long> deptIdList = StringUtil.strToLongList(deptIds);
		List<Long> addUserIdsList = StringUtil.strToLongList(addUserIds);
		List<Long> delUserIdsList = StringUtil.strToLongList(delUserIds);
		String data=ResolveRequest.getParameters(request);
		String ip=ResolveRequest.getIpAddress(request);

		//TODO 需要传入变化的userIds集合 List<Long> addUserIdsList  List<Long> delUserIdsList
		Map<String,List<String>> listMap= projectRoleService.grantRoleToUsers(roleId, userIdList, deptIdList,getProjectId(),data,ip,addUserIdsList,delUserIdsList);
		//保存操作日志
//		saveOperatLog(request, listMap);
		JSONData jsonData = new JSONData("人员分配成功！");
		return jsonData;
	}

	/**
	 * @Auhtor wly
	 * @Description: 角色人员分配，重构接口
	 * @Date: Created by 2019/12/31
	 */
	@ApiOperation("人员分配")
	@RequestMapping(value = "/grantRoleToUsersV3", method = RequestMethod.POST)
	public JSONData grantRoleToUsersV3(@RequestBody RoleUserDTO roleUserDTO, HttpServletRequest request) throws Exception {
		String data=roleUserDTO.toString();
		String ip=ResolveRequest.getIpAddress(request);
		Map<String,List<String>> listMap= projectRoleService.grantUsers(roleUserDTO, data, ip,getProjectId());
		//保存操作日志
//		saveOperatLog(request, listMap);
		JSONData jsonData = new JSONData("人员分配成功！");
		return jsonData;
	}

//	private void saveOperatLog(HttpServletRequest request, Map<String, List<String>> listMap) {
//		HttpSession session = request.getSession();
//		CurrentUser currentUser = (CurrentUser) session.getAttribute(SessionConstant.CURRENT_USER_KEY);
//		List<String> addName=listMap.get("adduser");
//		List<String> delName=listMap.get("deluser");
//		StringBuilder stringBuilder=new StringBuilder();
//		if(addName!=null&&addName.size()>0){
//			stringBuilder.append("增加了人员");
//			stringBuilder.append(addName.toString());
//		}
//		if(delName!=null&&delName.size()>0){
//			stringBuilder.append("删除了人员");
//			stringBuilder.append(delName.toString());
//		}
//		Map<String,Object> jsonParam = new HashMap<>();
//		jsonParam.put("userId", currentUser.getUser().getUserId());
//		SysGroup sysGroup=(SysGroup) currentUser.getGroup();
//		ISysUser sysUser=currentUser.getUser();
//		SysDeptment sysDeptment=(SysDeptment) currentUser.getDeptment();
//		jsonParam.put("userName",new StringBuilder(org.apache.commons.lang.StringUtils.isNotBlank(sysGroup.getFullPath())? sysGroup.getFullPath() :"").append("\\").append(sysDeptment != null?(org.apache.commons.lang.StringUtils.isNotBlank(sysDeptment.getFullPath())? sysDeptment.getFullPath() :""):"")
//				.append("\\").append(org.apache.commons.lang.StringUtils.isNotBlank(sysUser.getUserName())? sysUser.getUserName() :"").toString().replaceAll("/", "\\\\"));
//		jsonParam.put("websiteId",currentUser.getProject()!=null?currentUser.getProject().getProjectId():"");
//		if(currentUser.getProject()!=null) {
//			jsonParam.put("websiteName", currentUser.getProject().getProjectName());
//		}
//		//jsonParam.put("thirdPartyId", "CLOUD_CCUAP"+"_"+bizLog.getLogId());
//		jsonParam.put("moduleCode", "CLOUD_CCUAP");
//		jsonParam.put("operateDesc", stringBuilder.toString());
//		jsonParam.put("customName", currentUser.getGroup().getGroupName());
//		jsonParam.put("customCode", currentUser.getGroup().getGroupNo());
//		jsonParam.put("operateType", OperateEnum.ADD.getType());
//		jsonParam.put("operateTime", System.currentTimeMillis());
//		jsonParam.put("operateIp", currentUser.getIp());
//		jsonParam.put("operateUrl", request.getServletPath());
//		jsonParam.put("operateResult", "成功");
//		HttpHeaders headers = new HttpHeaders();
//		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
//		headers.setContentType(type);
//		headers.add("Accept", MediaType.APPLICATION_JSON.toString());
//		headers.add("token", YunQingConfigurer.TenantAccessheader);
//		HttpEntity<Map<String, Object>> formEntity= new HttpEntity<Map<String, Object>>(jsonParam, headers);
//		yqService.saveLog(formEntity);
//	}

}
